package com.haohope.framework.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;

public class HttpUtil {
	/**
	Collection<Part> parts = request.getParts();
	for(Part part:parts) {
		//Long size = part.getSize();
		//String name = part.getName();
		String submittedFileName = part.getSubmittedFileName();
		if(!StringUtils.isEmpty(submittedFileName) && (
				submittedFileName.toLowerCase().endsWith(".xls")
				||
				submittedFileName.toLowerCase().endsWith(".xlsx")
				)) {
			importexcel(request, response, part.getInputStream(), submittedFileName);
			break;
		}
	}
	 * @throws ServletException 
	 * @throws IOException 
	**/
	public static void createUploadParam(HttpServletRequest request) throws IOException, ServletException {
		Collection<Part> parts = request.getParts();
	}
	@SuppressWarnings("unchecked")
	public static Object createGetParams(HttpServletRequest request,Class clazz) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		if(null==clazz)clazz = Map.class;
		Enumeration<String> enums = request.getParameterNames();
		if(enums.hasMoreElements()) {
			String key = "";
			JSONObject json = new JSONObject();
			while(enums.hasMoreElements()) {
				key = enums.nextElement();
				json.put(key, request.getParameter(key));
			}
			return JSON.parseObject(json.toString(), clazz);
		}
		return null;
	}
	private static String contentType(HttpServletRequest request) {
		String contentType = request.getContentType();
		if(!StringUtils.isEmpty(contentType)) {
			contentType = contentType.split(";")[0];
		}
		return contentType;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object createPostParams(HttpServletRequest request,Class clazz) throws IOException {
		if(null==clazz)clazz = Map.class;
		String contentType = contentType(request);
        // json格式 json格式需要从request的输入流中解析获取
        if ("application/json".equalsIgnoreCase(contentType)) {
            // 使用 commons-io中 IOUtils 类快速获取输入流内容
            String jsonstr = IOUtils.toString(request.getInputStream(), "UTF-8");
            try {
            	return JSON.parseObject(jsonstr, clazz);
            }catch(Exception e) {
            }
        }
        return null;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object createFormParams(HttpServletRequest request,Class clazz) throws FileUploadException, JSONException, UnsupportedEncodingException {
		if(null==clazz)clazz = Map.class;
		// 获取内容格式
		String contentType = contentType(request);
        // form表单格式  表单形式可以从 ParameterMap中获取
        if ("multipart/form-data".equalsIgnoreCase(contentType)) {
        	DiskFileItemFactory factory = new DiskFileItemFactory();
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		List<FileItem> fileItems = upload.parseRequest(request);
    		JSONObject json = new JSONObject();
    		for (FileItem item:fileItems) {
    			if (item.isFormField()){
    				json.put(item.getFieldName(), new String(item.get(),"UTF-8"));
				}
    		}
    		return JSON.parseObject(json.toString(), clazz);
        }
        return null;
	}
	/**
	   * 向客户端响应
	 * @param response
	 * @param object
	 * @throws IOException
	 */
	public static void send(HttpServletResponse response, Object object)
			throws IOException {
		if (!response.isCommitted()) {
			response.setCharacterEncoding("UTF-8");
			ServletOutputStream outputStream = response.getOutputStream();
			if (object instanceof InputStream) {
				InputStream len = (InputStream) object;
				try {
					response.setHeader("Content-Encoding", "gzip");
					GZIPOutputStream bytes = new GZIPOutputStream(outputStream);
					try {
						IOUtils.copy(len, bytes);
					} finally {
						bytes.close();
					}
				} finally {
					len.close();
				}
			} else {
				byte[] bytes1;
				if (object instanceof byte[]) {
					bytes1 = (byte[]) object;
				} else {
					String gos;
					if (object == null) {
						gos = "";
					} else if(object instanceof String){
						gos = object.toString();
					} else {
						gos = JSON.toJSONString(object);
					}
					bytes1 = gos.getBytes("utf-8");
					if (StringUtils.isEmpty(response.getContentType())) {
						response.setContentType("text/html;charset=utf-8");
					}
				}
				response.setHeader("Content-Encoding", "gzip");
				GZIPOutputStream gos1 = new GZIPOutputStream(outputStream);
				try {
					gos1.write(bytes1);
				} finally {
					gos1.close();
				}
			}
			response.flushBuffer();
		}
	}
}
